<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common>
      <div class="wb-form-score" @click.stop>
        <van-form @submit="onSubmit" @failed="onFailed">
          <div v-for="(item_, index) in formLists" :key="index">
            <div :style="getFStyle(item_, index)" class="margin-top-30">
              <h4 v-html="getTitle(item_, index)" :style="getTitleStyle(item_)"></h4>
              <img class="form-img" v-if="item_.imgUrl" :src="item_.imgUrl">
              <div v-if="item_.type == FORM_TYPES_MAP.radio" :name="item_.tableKey" :border="false">
                <van-radio-group v-model="scoreFormValues[item_.tableKey]">
                  <van-radio v-for="(option, oindex) in item_.options" :key="'radio_' + oindex" :data-color="item_.color" :data-status="item_.status[oindex]" :name="option" :ref="radiosRefs" :checked-color="item_.color">{{option}}</van-radio>
                </van-radio-group>
              </div>
              <div v-if="item_.type == FORM_TYPES_MAP.checkbox" :name="item_.tableKey" :border="false">
                <van-checkbox-group v-model="scoreFormValues[item_.tableKey]" :max="item_.max">
                  <van-checkbox shape="square" v-for="(option, oindex) in item_.options" :key="'checkbox_' + oindex" :name="option" :data-color="item_.color" :data-status="item_.status[oindex]" :ref="checkboxsRefs" :checked-color="item_.color">{{option}}</van-checkbox>
                </van-checkbox-group>
              </div>
              <div v-if="!isH5Edit && commonAttr.isViewAnswer" class="answer-con">
                <p><strong>我的答案：</strong>{{ getMyQuestionStr(item_) }} </p>
                <p><strong>正确答案：</strong>{{ getRightQuestionStr(item_) }} </p>
                <p><strong>答案说明：</strong>{{ item_.info }} </p>
              </div>
            </div>
          </div>
          <div v-if="!commonAttr.isViewAnswer" class="margin-20 margin-top-50"><van-button round block type="info" native-type="submit" :style="btnStyles">提交</van-button></div>
        </van-form>
      </div>
    </template>
  </inject-template>
</template>

<script>
import { EventBus } from '@/store/index'
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { wbBase } from '@/components/utils/wbBase'
import { FORM_RANDOM_COLORS, FORM_RIGHT_COLOR, FORM_WRONG_COLOR, FORM_ITEM_STATUS, FORM_TYPES_MAP } from '@/common/const-form'
import { h, defineComponent, createApp } from 'vue'
import { onBeforeUpdate, reactive } from 'vue'
import { getCompIdByParam } from '@/plugins/utils'

export default {
  name: "WbFormScore",
  mixins: [utils, wbBase],
  setup () {
    let radiosRefs = []
    let checkboxsRefs = []
    const setRadiosRef = el => {
      radiosRefs.push(el)
    }
    const setCheckboxsRef = el => {
      checkboxsRefs.push(el)
    }
    onBeforeUpdate(() => {
      radiosRefs = []
      checkboxsRefs = []
    })
    return {
      radiosRefs,
      checkboxsRefs,
      setRadiosRef,
      setCheckboxsRef,
      formLists_: [],
      scoreFormItems: {},
      scoreFormValues: reactive({}),
      dropdownValue: '',
      dropdownKey: '',
      questionPrefixs: [],
      FORM_TYPES_MAP: FORM_TYPES_MAP,
    }
  },
  components: {
    InjectTemplate,
  },
  computed: {
    formLists: {
      get(){
        return this.formLists_;
      },
      set(lists_){
        this.formLists_ = lists_;
      }
    },
  },
  created() {
    this.setFormList();
  },
  mounted() {
    this.changeItemStyle(this.radiosRefs);
    this.changeItemStyle(this.checkboxsRefs);
  },
  methods: {
    changeItemStyle(items) {
      let icon;
      let radioOrCheckbox;
      let color = '';
      let name = '';
      _.forEach(items, (item) => {
        radioOrCheckbox = item.$el;
        icon = radioOrCheckbox.getElementsByClassName('van-icon')[0];
        icon.style.border = '1px solid ' + radioOrCheckbox.dataset.color;

        color = '';
        name = '';
        if(!this.isH5Edit && this.commonAttr.isViewAnswer){
          if(radioOrCheckbox.dataset.status == FORM_ITEM_STATUS.right){
            radioOrCheckbox.style.backgroundColor = FORM_RIGHT_COLOR;
            name = 'success';
            color = FORM_RIGHT_COLOR;
          }else if(radioOrCheckbox.dataset.status == FORM_ITEM_STATUS.wrong){
            radioOrCheckbox.style.backgroundColor = FORM_WRONG_COLOR;
            name = 'cross';
            color = FORM_WRONG_COLOR;
          }
          if(color){
            let span = document.createElement('span');
            radioOrCheckbox.appendChild(span);

            const IconComponent = defineComponent({
              render() {
                return h(Icon, { props: { name: name, color: '#fff', size: 24 } })
              }
            })
            let app = createApp(IconComponent);
            app.mount(span);
          }
        }
      });
    },
    getMyQuestionStr(item_){
      let optionStr = this.scoreFormValues[item_.serialName];
      let index = item_.options.indexOf(optionStr);
      if(index >= 0){
        return this.questionPrefixs[index];
      }else{
        return ''
      }
    },
    getRightQuestionStr(item_){
      let str = '';
      if(item_.type == FORM_TYPES_MAP.radio){
        str = this.questionPrefixs[item_.right];
      }else if(item_.type == FORM_TYPES_MAP.checkbox){
        let arr = item_.right.split(',');
        _.forEach(arr, (index) => {
          str += this.questionPrefixs[index] + ',';
        })
      }
      return str;
    },
    setFormList(){
      while(this.formLists_.length > 0){
        this.formLists_.pop();
      }
      this.questionPrefixs = this.commonAttr.questionPrefix ? this.commonAttr.questionPrefix.split(',') : ['A', 'B', 'C', 'D'];
      let item;
      let lists = this.lists;

      const relateAttrCompId = getCompIdByParam(this.commonAttr.relateAttrCompId);
      if(relateAttrCompId){
        let relateCompData = this.componentMap[relateAttrCompId];
        lists = relateCompData.lists;
      }
      if(!this.isH5Edit && this.commonAttr.isViewAnswer ){
        if(this.frontSelectScoreFormValues){
          lists = this.frontSelectScoreFormValues.scoreFormItems;
        }else if(this.interactionData.endScoreFormValues){
          let answerPrefixs = [];
          let id;
          //A,B,C,D
          let questionPrefixMapIndex = {};
          _.forEach(this.questionPrefixs, (questionPrefix, index) => {
            questionPrefixMapIndex[questionPrefix] = index;
          })
          let index = 0;
          _.forEach(this.interactionData.endScoreFormValues, (answerStr, key) => {
            id = _.trim(key, this.commonAttr.serialPrefix);
            index = id - 1;
            item = lists[index];
            this.initItem(item, index);
            answerPrefixs = answerStr.split(',');
            item.answerIndexs = [];
            _.forEach(answerPrefixs, (answerPrefix) => {
              item.answerIndexs.push(questionPrefixMapIndex[answerPrefix]);
            })
          })
        }
      }
      _.forEach(lists, (item_, index) => {
        if(!this.isH5Edit && this.commonAttr.isViewAnswer){
          item = item_;
          _.forEach(item.options, (option, index) => {
            item.status[index] = FORM_ITEM_STATUS.null;
            let answerIndexs = item.answerIndexs;
            if(answerIndexs){
              //我选择的答案
              _.forEach(answerIndexs, (answerIndex) => {
                if(index == answerIndex){
                  item.status[index] = FORM_ITEM_STATUS.wrong;
                }
              })
              //正确的答案
              if(item.rights.indexOf(_.toString(index)) != -1){
                item.status[index] = FORM_ITEM_STATUS.right;
              }
            }
          })
        }else{
          item = _.cloneDeep(item_);
          this.initItem(item, index);
        }
        this.formLists_.push(item);
        this.scoreFormItems[item.tableKey] = item;
      })
    },
    initItem(item, index){
      let colorLen = FORM_RANDOM_COLORS.length - 1;

      _.forEach(item.options, (option, index) => {
        item.options[index] = this.questionPrefixs[index] + '、' + option;
      })
      item.color = FORM_RANDOM_COLORS[index%colorLen];
      item.id = index + 1;
      item.serialName = this.commonAttr.serialPrefix ? this.commonAttr.serialPrefix + item.id : 'Q' + item.id;
      item.tableKey = item.serialName;
      item.rights = item.right.split(',');
      item.status = [];
    },
    onSubmit(values) {
      if(this.isH5Edit){
        return
      }
      //scoreFormItems values数据是一样的，values尽管没有选择也是有值的，为undefined
      for(let key in values){
        if(this.scoreFormItems[key]){
          if(!values[key]){
            this.showToast("亲，" + this.scoreFormItems[key].serialName + " 还没有选哦！");
            return
          }
        }
      }
      
      let score = 0;
      let totalScore = 0;
      let item = null;
      _.forEach(this.scoreFormItems, (item_) => {
        totalScore += parseInt(item_.score)
      })
      let answerIndex = -1;
      
      _.forEach(this.scoreFormValues, (answers, key) => {
        item = this.scoreFormItems[key];
        item.answerIndexs = [];
        if(_.isArray(answers)){
          let rightLen = 0;
          _.forEach(answers, (answer) => {
            answerIndex = item.options.indexOf(answer);
            item.answerIndexs.push(answerIndex);
            if(item.right.indexOf(answerIndex) != -1){
              rightLen++;
            }
          })
          if(rightLen == item.rights.length){
            score += parseInt(item.score);
          }
        }else{
          answerIndex = item.options.indexOf(answers);
          item.answerIndexs.push(answerIndex);
          if(item.right.indexOf(answerIndex) != -1){
            score += parseInt(item.score);
          }
        }
      })

      let data_str = { bizType: 'answer', score , full_score: totalScore };
      _.forEach(this.scoreFormValues, (strs, key) => {
        if(_.isArray(strs)){
          data_str[key] = '';
          _.forEach(strs, (str) => {
            data_str[key] += str.split('、')[0] + ',';
          })
        }else{
          data_str[key] = strs.split('、')[0];
        }
      })
      let params_ = { data_str: JSON.stringify(data_str), com_id: this.item.id };
      this.post("/Feact/formdata/", params_);

      let percent = _.size(this.scoreFormValues)/this.lists.length * 100 + '%';
      let data = { score, percent, totalScore };
      this.$store.commit('updateFormValue', {id: this.item.id, data})
      this.$store.commit("updateFrontSelectScoreFormValues", { scoreFormValues: this.scoreFormValues, scoreFormItems: this.scoreFormItems });
      EventBus.$emit("itemClick", {id: this.item.id, index: 0});
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    getFStyle(){
      return {
        color: this.item.styles.color,
        fontSize: this.item.styles.fontSize,
        textAlign: this.item.styles.textAlign,
      }
    },
    getTitle(item_){
      let title = '<span style="color:' + item_.color + '">' + item_.serialName + '、 </span>' + item_.name;
      if(item_.type == "checkbox"){
        title += ' <span class="grey-text">(多选 ' + item_.score + '分)</span>'
      }else if(item_.type == "radio"){
        title += ' <span class="grey-text">(单选 ' + item_.score + '分)</span>'
      }
      return title;
    },
    getTitleStyle(item_){
      return {
        borderBottom: '2px solid ' + item_.color,
      }
    }
  },
};
</script>

<style lang="scss">
.wb-form-score {
  width: inherit;
  height: inherit;

  .grey-text{
    color:#aaa;
    font-size: var(--size-24);
  }
  .answer-con{
    border: var(--size-2) solid #dddddd;
    border-radius: var(--size-20);
    padding: var(--size-20);
    margin: var(--size-20);
  }
  .form-img{
    width: 100%;
    object-fit: contain;
  }

  .checkbox-other{
    .van-cell{
      border: var(--size-2) solid #c8c9cc;
      border-top: none;
    }
  }
  .van-cell{
    padding: var(--size-10) var(--size-20);
    font-size: inherit;
  }
  .van-radio-group, .van-checkbox-group{
    width: 100%;
    padding: 4px 8px;
  }
  .van-radio, .van-checkbox{
    width: 100%;
    margin-top: var(--size-10);
    background-color: #f1f3f7;
    padding: var(--size-20) var(--size-20);
    border-radius: var(--size-12);
  }
  .van-radio__label, .van-checkbox__label{
    width: 90%;
  }
  .van-checkbox{
    margin-top: var(--size-10);
  }
  .van-hairline--top-bottom::after, .van-hairline-unset--top-bottom::after{
    border: none;
  }
  h4{
    text-align: left;
    margin-bottom: var(--size-10);
    font-size: inherit;
  }
  .van-radio__label{
    font-size: inherit;
  }
  .float-right{
    float: right;
  }
  .van-radio, .van-checkbox {
    margin-bottom: var(--size-8);
  }
  .van-checkbox__icon .van-icon, .van-radio__icon .van-icon{
    font-size: inherit;
    font-weight: inherit;
    font-style: inherit;
    width: inherit;
  }
}
</style>
